<template>
  <el-drawer
    v-model="visible"
    :title="t('share.detail.title')"
    :size="drawerSize"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <div class="drawer-content">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane :label="t('share.detail.settings.title')" name="settings">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            label-position="left"
          >
        <el-form-item :label="t('share.detail.settings.fileName')">
          <span>{{ form.fileName }}</span>
        </el-form-item>
        <el-form-item :label="t('share.detail.settings.shareType')" prop="shareType">
          <el-radio-group v-model="form.shareType">
            <el-radio label="PUBLIC">{{ t('share.detail.settings.publicShare') }}</el-radio>
            <el-radio label="PASSWORD">{{ t('share.detail.settings.passwordShare') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.shareType === 'PASSWORD'"
          :label="t('share.detail.settings.accessPassword')"
          prop="password"
        >
          <div class="password-input-container">
            <el-input
              v-model="form.password"
              :type="passwordVisible ? 'text' : 'password'"
              :placeholder="isPasswordEncrypted(originalPassword) ? t('share.detail.settings.passwordSetPlaceholder') : t('share.detail.settings.passwordPlaceholder')"
              clearable
            >
              <template #suffix>
                <el-button
                  link
                  @click="togglePasswordVisibility"
                  :icon="passwordVisible ? 'Hide' : 'View'"
                  size="small"
                >
                  {{ passwordVisible ? t('share.detail.settings.hidePassword') : t('share.detail.settings.showPassword') }}
                </el-button>
              </template>
            </el-input>
            <div v-if="isPasswordEncrypted(originalPassword)" class="password-hint">
              <el-text type="info" size="small">
                <el-icon><InfoFilled /></el-icon>
                {{ t('share.detail.settings.passwordSetPlaceholder') }}
              </el-text>
            </div>
            <div v-else-if="originalPassword && form.password === originalPassword" class="password-hint">
              <el-text type="info" size="small">
                <el-icon><InfoFilled /></el-icon>
                {{ t('share.detail.settings.passwordSetPlaceholder') }}
              </el-text>
            </div>
            <div v-if="form.password && (form.password !== originalPassword || isPasswordEncrypted(originalPassword))" class="password-hint">
              <el-text type="warning" size="small">
                <el-icon><Warning /></el-icon>
                {{ isPasswordEncrypted(originalPassword) ? t('share.messages.newPasswordSet') : t('share.messages.passwordChanged') }}
              </el-text>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="t('share.detail.settings.expiryTime')" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            :placeholder="t('common.selectTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="expireShortcuts"
          />
        </el-form-item>
        <el-form-item :label="t('share.detail.settings.maxAccess')">
          <el-switch
            v-model="form.hasAccessLimit"
            @change="handleAccessLimitChange"
          />
        </el-form-item>
        <el-form-item
          v-if="form.hasAccessLimit"
          :label="t('share.detail.settings.customCount')"
          prop="maxAccessCount"
        >
          <el-input-number
            v-model="form.maxAccessCount"
            :min="1"
            :max="999"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item :label="t('share.detail.settings.allowDownload')">
          <el-switch v-model="form.allowDownload" />
        </el-form-item>
        <el-form-item :label="t('share.detail.settings.allowPreview')">
          <el-switch v-model="form.allowPreview" />
        </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane :label="t('share.detail.accessLog.title')" name="logs">
          <div class="access-logs">
            <div class="logs-header">
              <span>{{ t('share.detail.accessLog.title') }}</span>
              <el-button size="small" @click="fetchAccessLogs">{{ t('common.refresh') }}</el-button>
            </div>
            <div class="logs-content">
              <el-table :data="accessLogs" v-loading="logsLoading" :empty-text="t('share.detail.accessLog.noRecords')">
                <el-table-column prop="accessTime" :label="t('share.detail.accessLog.accessTime')" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.accessTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="ipAddress" :label="t('share.detail.accessLog.ipAddress')" width="120" />
                <el-table-column prop="actionType" :label="t('share.detail.accessLog.actionType')" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getActionTypeColor(row.actionType)" size="small">
                      {{ getActionTypeText(row.actionType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="userAgent" :label="t('share.detail.accessLog.userAgent')" show-overflow-tooltip />
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visible = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ loading ? t('share.detail.settings.saving') : t('share.detail.settings.saveChanges') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, Warning } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import type { ShareInfo } from '@/types/share'
import { updateShare, getShareAccessLogs } from '@/api/modules/share'
import { useShareStore } from '@/stores/shareStore'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const shareStore = useShareStore()
const activeTab = ref('settings')

// 访问日志相关
const accessLogs = ref([])
const logsLoading = ref(false)

// 密码相关状态
const passwordVisible = ref(false)
const originalPassword = ref('')

const drawerSize = computed(() => {
  return window.innerWidth <= 768 ? '90%' : '500px'
})

const form = reactive({
  id: 0,
  fileName: '',
  shareType: 'PUBLIC' as 'PUBLIC' | 'PASSWORD',
  password: '',
  expireTime: '',
  hasAccessLimit: false,
  maxAccessCount: 1,
  allowDownload: true,
  allowPreview: true
})

const rules = {
  shareType: [
    { required: true, message: '请选择分享类型', trigger: 'change' }
  ],
  password: [
    {
      required: true,
      message: '请输入访问密码',
      trigger: 'blur',
      validator: (_: any, value: string) => {
        if (form.shareType === 'PASSWORD' && !value) {
          return false
        }
        return true
      }
    }
  ],
  maxAccessCount: [
    {
      required: true,
      message: '请输入最大访问次数',
      trigger: 'blur',
      validator: (_: any, value: number) => {
        if (form.hasAccessLimit && !value) {
          return false
        }
        return true
      }
    }
  ]
}

const expireShortcuts = [
  {
    text: '一天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    }
  },
  {
    text: '一周',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    }
  },
  {
    text: '一个月',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
      return date
    }
  }
]

const handleAccessLimitChange = (val: boolean) => {
  if (!val) {
    form.maxAccessCount = 1
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true

    const params = {
      shareType: form.shareType,
      password: form.shareType === 'PASSWORD' ? form.password : undefined,
      expireTime: form.expireTime || undefined,
      maxAccessCount: form.hasAccessLimit ? form.maxAccessCount : undefined,
      allowDownload: form.allowDownload,
      allowPreview: form.allowPreview
    }

    await updateShare(form.id, params)
    ElMessage.success('保存成功')
    shareStore.fetchShareList()
    visible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 获取访问日志
const fetchAccessLogs = async () => {
  if (!form.id) return

  logsLoading.value = true
  try {
    const response = await getShareAccessLogs(form.id, { page: 0, size: 50 })
    accessLogs.value = response.data.content || []
  } catch (error) {
    console.error('获取访问日志失败:', error)
    ElMessage.error('获取访问日志失败')
    accessLogs.value = []
  } finally {
    logsLoading.value = false
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 获取操作类型颜色
const getActionTypeColor = (type: string) => {
  switch (type) {
    case 'VIEW': return 'info'
    case 'PREVIEW': return 'success'
    case 'DOWNLOAD': return 'warning'
    default: return 'info'
  }
}

// 获取操作类型文本
const getActionTypeText = (type: string) => {
  switch (type) {
    case 'VIEW': return '查看'
    case 'PREVIEW': return '预览'
    case 'DOWNLOAD': return '下载'
    default: return '未知'
  }
}

// 检测密码是否为加密格式
const isPasswordEncrypted = (password: string) => {
  if (!password) return false
  // 检查是否为后端返回的加密标识或BCrypt格式
  return password === '***ENCRYPTED***' || /^\$2[ab]\$\d+\$/.test(password)
}

// 密码可见性切换
const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value
}

// 打开抽屉
const open = (share?: ShareInfo) => {
  if (share) {
    // 保存原始密码用于比较
    originalPassword.value = share.password || ''

    // 如果密码是加密格式，在表单中显示为空，让用户重新输入
    const displayPassword = isPasswordEncrypted(share.password) ? '' : (share.password || '')

    Object.assign(form, {
      id: share.id,
      fileName: share.fileName,
      shareType: share.shareType,
      password: displayPassword,
      expireTime: share.expireTime || '',
      hasAccessLimit: !!share.maxAccessCount,
      maxAccessCount: share.maxAccessCount || 1,
      allowDownload: share.allowDownload,
      allowPreview: share.allowPreview
    })
  } else {
    Object.assign(form, {
      id: 0,
      fileName: '',
      shareType: 'PUBLIC',
      password: '',
      expireTime: '',
      hasAccessLimit: false,
      maxAccessCount: 1,
      allowDownload: true,
      allowPreview: true
    })
    // 重置原始密码
    originalPassword.value = ''
  }
  visible.value = true
  activeTab.value = 'settings'
  passwordVisible.value = false

  // 如果是编辑模式，获取访问日志
  if (share) {
    fetchAccessLogs()
  }
}

defineExpose({
  open
})
</script>

<style lang="scss">
@import '@/styles/index.scss';

:deep(.el-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-drawer__body {
    padding: 0;
    display: flex;
    flex-direction: column;
  }

  .el-drawer__footer {
    padding: 16px 20px;
    border-top: 1px solid var(--el-border-color-light);
  }
}

.drawer-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;

  @include respond-to('sm') {
    padding: 16px;
  }

  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 20px;

      @include respond-to('sm') {
        margin-bottom: 16px;
      }
    }

    .el-radio-group {
      @include respond-to('sm') {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
    }

    .el-date-editor {
      width: 100%;
    }
  }
}

.drawer-footer {
  @include flex-end;
  gap: 12px;

  @include respond-to('sm') {
    @include flex-center;
    gap: 16px;

    .el-button {
      flex: 1;
    }
  }
}

.detail-tabs {
  height: 100%;

  :deep(.el-tabs__content) {
    height: calc(100% - 40px);
    overflow-y: auto;
  }
}

.access-logs {
  height: 100%;
  display: flex;
  flex-direction: column;

  .logs-header {
    @include flex-between;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-border-color-light);

    span {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }

  .logs-content {
    flex: 1;
    overflow: hidden;

    :deep(.el-table) {
      height: 100%;
    }
  }
}

.password-input-container {
  .password-hint {
    margin-top: 8px;

    .el-text {
      @include flex-start;
      gap: 4px;
      font-size: 12px;
    }
  }
}
</style>